package com.ohimy.dao;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public abstract class GenericDaoImpl<T extends Serializable, PK extends Serializable>
		extends HibernateDaoSupport implements IGenericDao<T, PK> {

	private Class<T> clazz;

	@SuppressWarnings("unchecked")
	public GenericDaoImpl() {
		this.clazz = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	public Class<T> getClazz() {
		return clazz;
	}

	public void delete(T entity) {
		getHibernateTemplate().delete(entity);
	}

	public void flush() {
		getHibernateTemplate().flush();
	}

	@SuppressWarnings("unchecked")
	public T get(PK id) {
		return (T) getHibernateTemplate().get(getClazz(), id);
	}

	@SuppressWarnings("unchecked")
	public T getWithLock(PK id, LockMode mode) {
		return (T) getHibernateTemplate().get(getClazz(), id, mode);

	}

	@SuppressWarnings("unchecked")
	public T load(final PK id) {
		return (T) getHibernateTemplate().load(getClazz(), id);
	}

	@SuppressWarnings("unchecked")
	public T loadWithLock(PK id, LockMode mode) {
		return (T) getHibernateTemplate().load(getClazz(), id, mode);
	}

	public Long save(T entity) {
		return (Long) getHibernateTemplate().save(entity);
	}

	public void persist(T entity) {
		getHibernateTemplate().persist(entity);
	}

	public Long merge(T entity) {
		return (Long) getHibernateTemplate().merge(entity);
	}

	public T saveOrUpdate(T entity) {
		getHibernateTemplate().saveOrUpdate(entity);
		return entity;
	}

	public T update(T entity) {
		getHibernateTemplate().update(entity);
		return entity;
	}

	public List<T> findAll() {
		return findByCriteria();
	}

	@SuppressWarnings("unchecked")
	public List<T> findByExample(T exampleEntity) {
		return getHibernateTemplate().findByExample(exampleEntity);
	}

	@SuppressWarnings("unchecked")
	public List<T> findByExample(T exampleEntity, String[] excludeProperty) {
		DetachedCriteria criteria = DetachedCriteria.forClass(getClazz());
		Example example = Example.create(exampleEntity);
		for (String exclude : excludeProperty) {
			example.excludeProperty(exclude);
		}
		criteria.add(example);
		return getHibernateTemplate().findByCriteria(criteria);
	}

	@SuppressWarnings("unchecked")
	public List<T> findLikeEntity(T entity, String[] propertyNames) {
		DetachedCriteria criteria = DetachedCriteria.forClass(getClazz());
		for (String property : propertyNames) {
			try {
				Object value = PropertyUtils.getProperty(entity, property);
				if (value instanceof String) {
					criteria.add(Restrictions.like(property, (String) value,
							MatchMode.ANYWHERE));
					criteria.addOrder(Order.asc(property));
				} else {
					criteria.add(Restrictions.eq(property, value));
					criteria.addOrder(Order.asc(property));
				}
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
		}
		return getHibernateTemplate().findByCriteria(criteria);
	}

	@SuppressWarnings("unchecked")
	public List findByHQL(String hql) {
		return getHibernateTemplate().find(hql);
	}

	@SuppressWarnings("unchecked")
	public List<T> findByCriteria(final int firstResult, final int maxResults,
			final Order order, final Criterion... criterions) {
		return (List<T>) getHibernateTemplate().execute(
				new HibernateCallback() {

					public List<T> doInHibernate(Session session)
							throws HibernateException, SQLException {
						Criteria criteria = session.createCriteria(getClazz());
						for (Criterion c : criterions) {
							criteria.add(c);
						}
						if (order != null) {
							criteria.addOrder(order);
						}

						criteria.setFirstResult(firstResult);
						criteria.setMaxResults(maxResults);

						return criteria.list();
					}
				});
	}

	@SuppressWarnings("unchecked")
	public List<T> findByCriteria(Criterion... criterions) {
		DetachedCriteria criteria = DetachedCriteria.forClass(getClazz());
		for (Criterion c : criterions) {
			criteria.add(c);
		}
		return getHibernateTemplate().findByCriteria(criteria);
	}

	@SuppressWarnings("unchecked")
	public List<T> findByCriteria(DetachedCriteria criteria) {
		return getHibernateTemplate().findByCriteria(criteria);
	}

	public void refresh(T entity) {
		getHibernateTemplate().refresh(entity);
	}

}
